<template>
	<view class="layout">
		<view class="content">
			<scroll-view scroll-y="true" class="scrollView">
				<view v-for="item in wordsList" :key="item.number">
					<view class="item">
						<text>{{item.word}}</text>
						<view class="iconBtnRow">
							<view :class="[item.statu == 1 ? 'leftBtn' : 'inactive-leftBtn']"  @click="onConfirm(item.number)">
								<uni-icons type="checkmarkempty" size="30" color="white"></uni-icons>
							</view>
							<view :class="[item.statu == 2 ? 'rightBtn' : 'inactive-rightBtn']"  @click="onDeny(item.number)">
								<uni-icons type="closeempty" size="30" color="white"></uni-icons>
							</view>
						</view>
				
					</view>
				</view>
			</scroll-view>
			
		</view>
		<view class="bottom">
			<text v-if="!isFinished">{{wordsCount()}}个单词</text>
			<view v-else class="statistics">
				<view class="statisticsItem">
					<view class="label">
						总数
					</view>
					<view class="value">
						{{ wordsList.length }}
					</view>
				</view>
				<view>|</view>
				<view class="statisticsItem">
					<view class="label">
						错误
					</view>
					<view class="value">
						{{ wrongWordsCount }}
					</view>
				</view>
				<view>|</view>
				<view class="statisticsItem">
					<view class="label">
						准确率
					</view>
					<view class="value">
						{{ accuracy }}%
					</view>
				</view>
			</view>
			<view v-if="!isFinished" class="bottomBtn" @click="startRemember">
				开始识记
			</view>
			<view v-else class="bottomBtn" @click="onSummit">
				提交
			</view>
		</view>
	
		<uni-popup ref="tipsDialog" type="center" :is-mask-click="false">
			<view class="tipsDialog">
				<view class="dialogContent">
					<view class="dialogTitle">
						温馨提示
					</view>
					<view class="textIconColumn">
						<view class="textIconRow">
							<text>认识的词点对勾,标记为:</text>
							<view class="rightBtn">
								<uni-icons type="checkmarkempty" size="20" color="white"></uni-icons>
							</view>
						</view>
						<view class="textIconRow">
							<text>不熟悉的点叉号,标记为:</text>
							<view class="wrongBtn">
								<uni-icons type="closeempty" size="20" color="white"></uni-icons>
							</view>
						</view>
					</view>
					<view class="bottomTip">
						<text>点击开始标记后会把标记\n红叉的单词进行标记学习</text>
					</view>
					
				</view>
				<uni-icons type="clear" size="100rpx" @click="onCloseDialog"></uni-icons>
			</view>
		</uni-popup>
	</view>
	
</template>

<script setup>
	import {ref, computed} from "vue";
	import { words } from '../../static/words.js';
	import {onLoad, onUnload, onReady} from '@dcloudio/uni-app';
	import { useUserInfoStore } from '../../store';	
	import { useStudyInfoStore } from '../../store';
		
	//获得store实例对象
	const userInfoStore = useUserInfoStore()
	//获得store实例对象
	const studyInfoStore = useStudyInfoStore()
	
	let wordsList = ref([]);
	
	let isFinished = ref(false);
	
	const tipsDialog = ref(null);
	
	//错词 计算属性
	const wrongWordsCount = computed(() => {
		return wordsList.value.filter(item => item.statu === 2).length;
	})
	
	//准确率 计算属性
	const accuracy = computed(() => {
		return (wordsList.value.filter(item => item.statu === 1).length / wordsList.value.length * 100).toFixed(2);
	})
	
	// function wordsCount(){
	// 	return wordsList.value.filter(item => item.statu != 0).length;
	// }
	
	onLoad(async ()=>{
		//原始数据
		// let arr = getRandomItems(uni.getStorageSync("GaoKao3500"), 20);
		let arr = uni.getStorageSync("GaoKao3500");
		
		if(studyInfoStore.studyMode === 0){
			const res = await uniCloud.callFunction({
				name: "getStudyedWords",
				data: {
					relateUuid: userInfoStore.userInfo.uuid,
					wordBankId: "GaoKao3500"
				}
			})
			
			//提取word字段
			const tempArr = new Set(res.result.map(item => item.word));
				
			const resultArr = arr.filter(item => !tempArr.has(item.word))
			
			const randomArr = getRandomItems(resultArr, 20);
			
			//statu 0未选择 1确认 2否认
			wordsList.value = randomArr.map(item => {
				return {
					...item,
					statu: 0
				}
			})
		} else if(studyInfoStore.studyMode === 1) {
			isFinished.value = true;
			//从studyInfoStore中获取选择单词列表
			let studyWordsList = studyInfoStore.studyWordsList;
			
			//根据number从词库中赛选单词
			studyWordsList.forEach((item) => {
			    wordsList.value.push(
					{
						...arr.find(word => word.number === item),
						statu: 0
					}
				)
				
			})
			
			console.log(studyWordsList)
		}
				
		
		
	})
	
	onReady(()=>{
		console.log(studyInfoStore.studyMode)
		if(studyInfoStore.studyMode === 0){
			tipsDialog.value.open();
			setTimeout(()=>{
				uni.setNavigationBarTitle({
					title: "学新前检测",
					success: () => {
						console.log("设置标题成功")
					},
					fail: () => {
						console.log("设置标题失败")
					}
					
				})
			}, 100);
			// 监听事件
			uni.$on('finish',()=>{
				//需延迟 不然更不自带头部标题
				setTimeout(()=>{
					uni.setNavigationBarTitle({
						title: "学新后检测",
						success: () => {
							console.log("设置标题成功")
						},
						fail: () => {
							console.log("设置标题失败")
						}
						
					})
				}, 100);
				isFinished.value = true;
				wordsList.value = [];
				//从studyInfoStore中获取选择单词列表
				let arr = studyInfoStore.studyWordsList;
				let wordBank = uni.getStorageSync("GaoKao3500")
				//根据number从词库中赛选单词
				// arr.forEach((item)=>{
				// 	// wordsList.value.push(words.find(word => word.number === item))
				// 	let temp = wordBank.find(word => word.number === item);
				// 	console.log(temp)
				// 	wordsList.value.push({...item, statu: 0})
				// 	// wordsList.value.push({id:temp.id, word:temp.word, statu: 0});
				// })
				
				wordsList.value = arr.map(item => {
					let temp = wordBank.find(word => word.number === item);
					return {...temp, statu: 0}
				})
				
				console.log(wordsList.value)
				
			})
		} else if(studyInfoStore.studyMode === 1){
			setTimeout(()=>{
				uni.setNavigationBarTitle({
					title: "复习后检测",
					success: () => {
						console.log("设置标题成功")
					},
					fail: () => {
						console.log("设置标题失败")
					}
					
				})
			}, 100);
		}
		
	})
	
	onUnload(()=>{
		console.log("鞋子啊");
		studyInfoStore.clearStudyWordsList();
		// 移除监听事件
		uni.$off('finish'); 
	})
	

	
	// 随机抽取数据的方法
	function getRandomItems(array, count) {
	    // 首先复制数组，避免修改原数组
	    let copiedArray = array.slice();
	
	    // 用于存储随机抽取的数据
	    let result = [];
	
	    // 循环抽取指定数量的数据
	    for (let i = 0; i < count; i++) {
	        // 如果数组为空，跳出循环
	        if (copiedArray.length === 0) break;
	
	        // 随机生成一个索引
	        let randomIndex = Math.floor(Math.random() * copiedArray.length);
	
	        // 将随机选中的数据添加到结果数组中
	        result.push(copiedArray[randomIndex]);
	
	        // 从复制的数组中移除已经选中的数据
	        copiedArray.splice(randomIndex, 1);
	    }
	
	    return result;
	}
	
	//认识单词
	function onConfirm(number){
		console.log("确认");
		wordsList.value.find(temp => temp.number === number).statu = 1;
	}
	
	//不认识单词
	function onDeny(number){
		console.log("否认");
		wordsList.value.find(temp => temp.number === number).statu = 2;
	}
	
	function wordsCount(){
		return wordsList.value.filter(item => item.statu === 2).length;
	}
	
	//开始识记 跳转下一页
	async function startRemember() {
		console.log("开始识记");
		let unknownWordList = [];
		//用于请求
		let studyWordsList = [];
		wordsList.value.forEach((item, index) => {
			if(item.statu == 1) {
				studyWordsList.push({
					word: item.word,
					known: true
				});
			}
			else if(item.statu == 2){
				unknownWordList.push(item.number);
				//todo 请求增加已学单词
				studyWordsList.push({
					word: item.word,
					known: false,
					studyedNum: 0
				});
				
			}
		})
		if(unknownWordList.length === 0){
			uni.showToast({
				title: "没有生词",
				icon:"error"
			})
			return;
		}
		
		const res = await uniCloud.callFunction({
			name: "addNewStudyWord",
			data: {
				relateUuid: userInfoStore.userInfo.uuid,
				wordBankId: "GaoKao3500",
				studyedWords: studyWordsList
			}
		})
		
		studyInfoStore.setStudyWordsList(unknownWordList);


		uni.navigateTo({
			url:"/pages/memorize-words/memorize-words"
		})
	}
	
	//完成后提交
	async function onSummit(){
		if(wordsList.value.some(item => item.statu === 0)){
			uni.showToast({
				title: "存在未选单词",
				icon: "error"
			})
			return;
		}
		
		let studyedWords = wordsList.value.map(item => {
			return {
				word: item.word, 
				statu: item.statu
			}
		});
		console.log(studyedWords)
		
		const res = await uniCloud.callFunction({
			name: "updateStudyedwords",
			data: {
				relateUuid: userInfoStore.userInfo.uuid,
				wordBankId: "GaoKao3500",
				studyedWords: studyedWords
			}
		})
		
		if(studyInfoStore.studyMode === 0) {
			uni.navigateBack();
		} else if(studyInfoStore.studyMode === 1){
			uni.navigateBack(
				{
					delta: 2
				}
			);
		}
		
	}

	function onCloseDialog(){
		tipsDialog.value.close();
	}
</script>

<style lang="scss" scoped>
	.layout{
		background-color: #F5F5F5;
		height: 100vh;
		position: relative;
		.content{
			padding: 20rpx;
				
			.scrollView{
				height: 80vh;
				.item{
					margin: 20rpx 0;
					padding: 20rpx;
					font-size: 24px;
					background-color: white;
					display: flex;
					flex-direction: row;
					justify-content: space-between;
					.iconBtnRow{
						display: flex;
						gap: 30rpx;
						.leftBtn{
							background-color: #18BB7C;
							padding: 10rpx;
							border-radius: 50%;
						}
						.inactive-leftBtn{
							background-color: #94938F;
							padding: 10rpx;
							border-radius: 50%;
						}
						.rightBtn{
							background-color: #F6465D;
							padding: 10rpx;
							border-radius: 50%;
						}
						.inactive-rightBtn{
							background-color: #94938F;
							padding: 10rpx;
							border-radius: 50%;
						}
					}
				}
			}
			
		}
		.bottom{
			background-color: white;
			padding: 20rpx 40rpx 150rpx 40rpx;
			position: absolute;
			width: 100%;
			box-sizing: border-box;
			bottom: 0;
			display: flex;
			flex-direction: row;
			justify-content: space-between;
			
			text{
				font-size: 24px;
			}
			.statistics{
				display: flex;
				gap: 20rpx;
				align-items: center;

				.statisticsItem{
					display: flex;
					gap: 5rpx;
					.label{
						color: #18BB7C;
					}
					.value{
						color: red;
					}
				}

			}
			.bottomBtn{
				border: 1rpx solid black;
				border-radius: 50rpx;
				padding: 10rpx 20rpx;
				display: flex;
				justify-content: center;
				align-items: center;
			}
		}
		.tipsDialog{
			display: flex;
			flex-direction: column;
			align-items: center;
			gap: 30rpx;
			.dialogContent{
				display: flex;
				flex-direction: column;
				align-items: center;
				padding: 40rpx;
				background-color: white;
				border-radius: 50rpx;
				.dialogTitle{
					margin-bottom: 50rpx;
					padding: 15rpx 50rpx;
					border-radius: 50rpx;
					background-color: #18BB7C;
					color: white;
					font-size: 24px;
				}

				.textIconColumn{
					display: flex;
					flex-direction: column;
					gap: 30rpx;
					text{
						color: black;
						font-size: 20px;
					}
					.textIconRow{
						display: flex;
						gap: 20rpx;
						align-items: center;
						.rightBtn{
							background-color: #18BB7C;
							padding: 10rpx;
							border-radius: 50%;
						}
						.wrongBtn{
							background-color: #F6465D;
							padding: 10rpx;
							border-radius: 50%;
						}
					}
				}
					
				.bottomTip{
					margin-top: 60rpx;
					padding: 10rpx 40rpx;
					border-radius: 50rpx;
					border: 1rpx solid #efdd9c;
					background-color: #fce98c;
					text{
						font-size: 18px;
					}
				}
			}
			
		}
	}
</style>
